﻿using System;
using System.IO;

using PickGold.Data.Hsts.General.Extensions;

namespace PickGold.Data.Hsts.General.Persist
{
	public class BooleanIndexerPersist : IIndexerPersist<Boolean>
	{
		public const byte VERSION = 40;

		public void Store(BinaryWriter writer, Func<int, object, bool> values, int count, object state)
		{
			writer.Write(VERSION);

			byte[] buffer = new byte[(int)Math.Ceiling(count / 8.0)];

			for (int i = 0; i < count; i++)
				buffer.SetBit(i, values(i, state) ? 1 : 0);

			writer.Write(buffer);
		}

		public void Load(BinaryReader reader, Action<int, object, bool> values, int count, object state)
		{
			if (reader.ReadByte() != VERSION)
				throw new Exception("Invalid BooleanIndexerPersist version.");

			byte[] buffer = reader.ReadBytes((int)Math.Ceiling(count / 8.0));

			for (int i = 0; i < count; i++)
				values(i, state, buffer.GetBit(i) == 0 ? false : true);
		}
	}
}
